package com.my.lab.service;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.my.lab.util.ConfigConstant;
import com.my.lab.util.WifiUtil;

public class WlanService extends Service {

    private static final String TAG = "WlanService";

    private WifiUtil wifiUtil;

    private ScanWlanTask swt;

    private Timer timer;

    private Context context;
    
    private HashMap<String, Integer> infoMap = new HashMap<String, Integer>();

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Log.d(TAG, "onStart is called ...");
        super.onStart(intent, startId);
        context = this;
        wifiUtil = new WifiUtil(this);
        timer = new Timer();
        boolean wifiEnable = wifiUtil.isWifiEnabled();
        infoMap = wifiUtil.getScanResult();
        if (wifiEnable && infoMap.get(ConfigConstant.alis) != null && infoMap.get(ConfigConstant.alis) > 3
                && !wifiUtil.getSSID().equals(ConfigConstant.alis) ) {
            boolean result = wifiUtil.addNetwork(3, ConfigConstant.alis, ConfigConstant.psw);
            if(result)Toast.makeText(this, "添加网络:" + result, Toast.LENGTH_SHORT).show();
        } else if (wifiEnable && !wifiUtil.getSSID().equals(ConfigConstant.alis)) {
            timer.schedule(new ScanWlanTask(), 0, 10 * 1000);
        }
    }

    class ScanWlanTask extends TimerTask {

        @Override
        public void run() {
            Log.d(TAG, "ScanWlanTask scheduled .......");
            infoMap = wifiUtil.getScanResult();
            if (infoMap.get(ConfigConstant.alis) != null && infoMap.get(ConfigConstant.alis) > 3) {
                boolean result = wifiUtil.addNetwork(3, ConfigConstant.alis, ConfigConstant.psw);
                if(result) {
//                    Looper.prepare();
//                    Toast.makeText(context, "添加网络:" + result, Toast.LENGTH_SHORT).show();
                    this.cancel();
                }
            } else {
                return;
            }

        }

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand is called ...");
        return super.onStartCommand(intent, Service.START_STICKY, startId);
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy is called ...");
        startService(new Intent(this, WlanService.class));
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}
